const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')


//自动加载路由库
const Router = require('koa-router');
const fs = require('fs');
const path = require('path');

//跨域 问题 
const cors = require('koa2-cors')

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

// 添加跨域中间件
// 修改跨域中间件配置
app.use(cors({
  origin: function (ctx) {
    // return 'http://localhost:9527';
    return '*';  //默认设置全不允许，安全起见，建议改为特定域名
  },
  credentials: true,
  allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowHeaders: ['Content-Type', 'Authorization', 'Accept', 'X-Token', 'X-Requested-With'],
  exposeHeaders: ['WWW-Authenticate', 'Server-Authorization']
}));


app.use(views(__dirname + '/views', {
  extension: 'ejs'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
//自动加载路由
// 自动加载路由函数 
function loadRoutes(dir = 'routes') {
  const routesDir = path.join(__dirname, dir);
  // 读取 routes 目录下所有 .js 文件 
  const files = fs.readdirSync(routesDir).filter(file => file.endsWith('.js'));
  files.forEach(file => {
    const route = require(path.join(routesDir, file));
    // 假设每个路由文件导出一个 Router 实例
    if(route instanceof Router){
      app.use(route.routes()).use(route.allowedMethods());
    }else{
      console.log(file + '路由文件导出的不是 Router 实例');
    }
  });
}
// 调用函数加载路由 
loadRoutes();


// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
